import { Label, NodeEventType } from "cc";
import { UIModuleEnum } from "../../enum/UIDefine";
import { BaseUIView } from "../../game/base/BaseUIView";
import { Node } from "cc";
import { Button } from "cc";
import { EventTouch } from "cc";

interface IAlertData{
	noAlertType?: number, 
	titleStr?: string,
	canClose?:boolean
}

export class AlertView extends BaseUIView {
	private static _instance: AlertView;
	private _txtAlert: Label;
	private _btns: Node[];
	private _txtBtns: Label[];
	private _alertStr: string;
	private _callBack: Function;
	private _btnLabels: string[];
	private _btnTypes: AlertType[] = [];
	private _canClose:boolean;//是否可以不操作按钮关闭提示框界面
	public constructor() {
		super(UIModuleEnum.common, "AlertView");
	}

	public static get instance(): AlertView {
		return this._instance;
	}

	private setData(alertStr: string, param?: IAlertData, callBack: Function = null, btnLabels: string[] = null, btnTypes: AlertType[] = null): void {
		this._alertStr = alertStr;
		this._callBack = callBack;
		this._btnLabels = btnLabels;
		this._btnTypes = btnTypes;
		this._canClose = param && param.canClose;
	}

	public initUI(): void {
		this._btns = [];
		this._txtBtns = [];
		this._txtAlert = this.getChildByName("txtAlert").getComponent(Label);
		let btnsNode = this.getChildByName("btns");
		for (let i: number = 1; i <= 2; i++) {
			let btn: Node = btnsNode.getChildByName("btn_" + i);
			btn.on(Button.EventType.CLICK, this.onBtnClickHandler, this);
			btn.active = false;
			this._btns.push(btn);
			this._txtBtns.push(btn.getChildByName("Label").getComponent(Label));
		}
		let maskBg = this.getChildByName("maskBg");
		maskBg.on(NodeEventType.TOUCH_END,()=>{
			this._canClose && this.dealClick(-1);
		});
	}

	public onShowAfter(): void {
		this._txtAlert.string = this._alertStr;
		for (let i: number = 0; i < this._btns.length; i++) {
			let type = this._btnTypes[i];
			if(type) {
				this._btns[i].active = true;
				this._txtBtns[i].string = this._btnLabels[i];
			}
			else{
				this._btns[i].active = false;
			}
		}
	}

	private onBtnClickHandler(evt: EventTouch): void {
		let _index: number = this._btns.indexOf(evt.target);
		this.dealClick(this._btnTypes[_index]);
	}

	private dealClick(type:number){
		this.hide();
		this._callBack && this._callBack(type);
		this._callBack = null;
	}

	public hide(): void {
		super.hide();
	}

	/**
	 * @param alertStr 提示内容
	 * @param callBack 回调函数
	 * @param callBackObj 回调作用域
	 * @param btnTypes 按钮对应索引
	 * @param btnLabels 按钮文本
	 */
	public static show(alertStr: string, param?:IAlertData, callBack: Function = null, btnTypes: AlertType[] = [AlertType.NO, AlertType.YES], btnLabels: string[] = ["取消", "确定"]): AlertView {
		if (AlertView._instance == null) {
			AlertView._instance = new AlertView();
		}
		AlertView._instance.setData(alertStr, param, callBack, btnLabels, btnTypes);
		AlertView._instance.show();
		return AlertView._instance;
	}
}

export enum AlertType {
	/**确定 */
	YES = 1,
	/**取消 */
	NO = 2,
	TEST = 3,
}